package com.whacos.modules.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whacos.common.annotations.Log;
import com.whacos.common.controller.BaseController;
import com.whacos.common.enums.Constant;
import com.whacos.common.utils.BeanUtils;
import com.whacos.common.utils.StringUtils;
import com.whacos.common.vo.ResponseVO;
import com.whacos.modules.system.entity.SysTask;
import com.whacos.modules.system.service.SysTaskService;
import com.whacos.modules.system.vo.SysTaskVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiongdun
 * @description JobController
 * @since 2018/11/17 17:11
 */
@RequestMapping("/sys/job")
@Controller
@Slf4j
public class SysTaskController extends BaseController {
    @Autowired
    private SysTaskService sysTaskService;

    // @Log(value = "跳转到查询定时任务列表")
    @GetMapping()
    @RequiresPermissions("sys:job:job")
    public String job() {
        return "sys/job/job";
    }

    // @Log(value = "查询定时任务列表")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("sys:job:job")
    public IPage<SysTaskVO> list(SysTaskVO sysTaskVO) {
        // 查询列表数据
        IPage<SysTaskVO> sysTaskVOPage = new Page<>();
        try {
            // 转换请求参数对象
            // 查询
            IPage<SysTask> sysTaskPage = sysTaskService.page(new Page<>(sysTaskVO.getPageNum(), sysTaskVO.getPageSize()),
                    Wrappers.lambdaQuery(new SysTask())
                            .eq(StringUtils.isNotEmpty(sysTaskVO.getTaskName()), SysTask::getTaskName, sysTaskVO.getTaskName())
                            .orderByDesc(SysTask::getCronExpression));

            // 转换返回结果对象
            BeanUtils.copyPage(sysTaskPage, sysTaskVOPage);
            List<SysTaskVO> sysTaskVOList = new ArrayList<>();
            sysTaskPage.getRecords().forEach(source -> {
                SysTaskVO target = new SysTaskVO();
                BeanUtils.copyProperties(source, target);
                sysTaskVOList.add(target);
            });
            sysTaskVOPage.setRecords(sysTaskVOList);
        } catch (Exception e) {
            log.error("查询文件列表异常，异常原因：" + e.getMessage(), e);
        }
        return sysTaskVOPage;
    }

    // @Log(value = "跳转到新增定时任务")
    @GetMapping("/add")
    @RequiresPermissions("sys:job:add")
    public String add() {
        return "sys/job/add";
    }

    // @Log("跳转到编辑定时任务")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("sys:job:edit")
    public String edit(@PathVariable("id") Long id, Model model) {
        SysTask job = sysTaskService.getById(id);
        model.addAttribute("job", job);
        return "sys/job/edit";
    }

    // @Log("获取任务信息")
    @GetMapping("/info/{id}")
    @RequiresPermissions("sys:job:job")
    public ResponseVO info(@PathVariable("id") Long id) {
        SysTask taskScheduleJob = sysTaskService.getById(id);
        return ResponseVO.success().put("taskScheduleJob", taskScheduleJob);
    }

    @Log("保存任务信息")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("sys:job:add")
    public ResponseVO save(SysTaskVO sysTaskVO) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            SysTask sysTask = new SysTask();
            BeanUtils.copyProperties(sysTaskVO, sysTask);

            // 保存结果
            sysTask.createdData(this.getUserId());
            if (sysTaskService.save(sysTask)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, "删除失败");
        }
        return ResponseVO.error();
    }

    @Log("修改任务信息")
    @ResponseBody
    @PostMapping("/update")
    @RequiresPermissions("sys:job:edit")
    public ResponseVO update(SysTaskVO sysTaskVO) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            SysTask sysTask = new SysTask();
            BeanUtils.copyProperties(sysTaskVO, sysTask);

            // 保存结果
            sysTask.updatedData(this.getUserId());
            if (sysTaskService.updateById(sysTask)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, "删除失败");
        }
        return ResponseVO.error();
    }

    @Log("删除任务信息")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("sys:job:remove")
    public ResponseVO remove(@RequestParam(value = "id") Long id) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            if (sysTaskService.removeById(id)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, "删除失败");
        }
        return ResponseVO.success();
    }

    @Log("批量删除任务信息")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("sys:job:batchRemove")
    public ResponseVO batchRemove(@RequestParam("ids[]") List<Long> ids) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            if (sysTaskService.removeByIds(ids)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, "删除失败");
        }
        return ResponseVO.success();
    }

    @Log("修改任务状态信息")
    @PostMapping(value = "/changeJobStatus")
    @ResponseBody
    @RequiresPermissions("sys:job:edit")
    public ResponseVO changeJobStatus(Long id, String cmd) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        String label;
        if ("start".equals(cmd)) {
            label = "启动";
        } else {
            label = "停止";
        }
        try {
            sysTaskService.changeStatus(id, cmd);
            return ResponseVO.success("任务" + label + "成功");
        } catch (Exception e) {
            return ResponseVO.error("任务" + label + "失败");
        }
    }

    @Log("修改任务启动时间信息")
    @PostMapping(value = "/changeJobCron")
    @ResponseBody
    @RequiresPermissions("sys:job:edit")
    public ResponseVO changeJobCron(Long id, String cron) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        if (StringUtils.isEmpty(cron)) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, "任务cron修改失败");
        }
        try {
            sysTaskService.updateCron(id, cron);
            return ResponseVO.success("任务cron修改成功");
        } catch (Exception e) {
            return ResponseVO.error("任务cron修改失败");
        }
    }
}
